﻿using System;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace aaAttributeBrowser
{
    public class Client : ObservableObject, IDisposable
    {
        private System.Threading.Timer _t;
        private string _server = "http://localhost:8123/";
        private string _objectName = "";
        private int _refreshInterval = 2000;
        private bool _autoRefresh = true;
        private bool _autoFetch = true;
        private aaObject _a2Object = null;
        private string _message = "";
        private bool _disposed = false;

        public bool LogDebugInfo { get; set; } = false;

        public String Server
        {
            get
            {
                return _server;
            }
            set
            {
                _server = value;
                RaisePropertyChanged(nameof(Server));
            }
        }
        public string ObjectName
        {
            get
            {
                return _objectName;
            }
            set
            {
                LogInfo("Entered ObjectName_Set " + value);
                //sometimes this will get set many times in a row to the same thing
                if (value != _objectName)
                {
                    _objectName = value;
                    RaisePropertyChanged(nameof(ObjectName));
                    if (AutoFetch)
                    {
                        GetObject();
                    }
                }
            }
        }
        public int RefreshInterval
        {
            get
            {
                return _refreshInterval;
            }
            set
            {
                _refreshInterval = value;
                RaisePropertyChanged(nameof(RefreshInterval));
            }
        }
        public bool AutoRefresh
        {
            get
            {
                return _autoRefresh;
            }
            set
            {
                _autoRefresh = value;
                RaisePropertyChanged(nameof(AutoRefresh));
            }
        }
        public bool AutoFetch
        {
            get
            {
                return _autoFetch;
            }
            set
            {
                _autoFetch = value;
                RaisePropertyChanged(nameof(AutoFetch));
            }
        }
        public aaObject A2Object
        {
            get
            {
                return _a2Object;
            }
            private set
            {
                _a2Object = value;
                RaisePropertyChanged(nameof(A2Object));
            }
        }
        public string Message
        {
            get
            {
                return _message;
            }
            private set
            {
                _message = value;
                RaisePropertyChanged(nameof(Message));
            }
        }

        public void Dispose()
        {
            LogInfo("Entered Dispose");
            _disposed = true;
            _t = null;

        }

        public void GetObject(string objectName = "")
        {
            if (!string.IsNullOrEmpty(objectName))
                _objectName = objectName;
            LogInfo("Entered GetObject");
            _t = new System.Threading.Timer(t_Tick, null, 0, System.Threading.Timeout.Infinite);
        }

        private void Request()
        {
            LogInfo("Entered Request");
            var request = WebRequest.Create(Server + "object/" + ObjectName);
            string result = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();

            aaObject obj = JsonConvert.DeserializeObject<aaObject>(result);
            if (obj.Name == ObjectName) //incase we have requested something else in the mean time
                A2Object = obj;
            if (A2Object.Attributes.Count == 0)
                Message = string.Format("Object {0} exists, but had no attributes.", A2Object.Name);
            else
                Message = "Success.";
        }

        private void t_Tick(object arg)
        {
            try
            {
                LogInfo("Entered t_Tick");
                Request();
                if (AutoRefresh & !_disposed)
                    _t.Change(RefreshInterval, System.Threading.Timeout.Infinite);
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        private void LogInfo(string message)
        {
            if (LogDebugInfo)
                File.AppendAllText("C:\\AttributeBrowserClientLog.txt", string.Format("{0} {1}: {2}{3}", this.GetHashCode().ToString(), DateTime.Now.ToString(), message, Environment.NewLine));
        }
    }
}
